<?php
/**
 * Created by PhpStorm.
 * User: Yangjinlei
 * Date: 2018/7/13
 * Time: 11:02
 */

namespace App\Http\Controllers\Admin;


use App\Exceptions\ServerException;
use App\Http\Controllers\ApiBaseController;
use App\Repositories\AdminRepository;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Exceptions\JWTException;

/**
 * @property AdminRepository repository
 */
class AuthController extends ApiBaseController
{
    public function __construct(AdminRepository $repository)
    {
        $this->repository = $repository;
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function login(Request $request)
    {
        $credentials = $request->only('name','password');
        try{
            if (!$token = auth('admin')->attempt($credentials)){
                return $this->failed(400,"用户名或者密码错误");
            }
        }catch (JWTException $exception){
            throw new ServerException("JWTException");
        }
        $user = $this->repository->findBy('name',$credentials['name']);
        $this->repository->update([
            'ip'=>$request->ip()
        ],$user->id);
        return $this->success(compact('token'));
    }

    public function logout(){
        auth('admin')->logout();
        return $this->success();
    }
}